package com.ncmmall.mall.controller.business.withdraw;

import com.ncmmall.application.business.withdraw.MerchantWithdrawApplication;
import com.ncmmall.domain.business.trading.MerchantWithdrawApply;
import com.ncmmall.domain.business.trading.QTradingLog;
import com.ncmmall.domain.business.trading.TradingLog;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提现管理
 *
 * @author likaikai
 * @date 2019-07-22 15:38:57
 */
@Controller
@RequestMapping("/merchant/withdraw")
public class MerchantWithdrawController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MerchantWithdrawApplication merchantWithdrawApplication;

    private final Logger logger = LoggerFactory.getLogger(MerchantWithdrawController.class);

    /**
     * 提现列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, MerchantWithdrawApply params) throws ParseException {

        WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class);
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());

        Map<String, Object> map = new HashMap<>();
        map.put("id", merchant.getId());

        String sql = buildSql("select r from MerchantWithdrawApply r where r.merchant.id = :id ", map, params);

        QueryPage<MerchantWithdrawApply> page = queryChannelService.findPage(sql, pageRequest.setParams(map), MerchantWithdrawApply.class);

        model.addAttribute("params", params);
        model.addAttribute("page", page);

        return "merchant/withdraw/list";
    }

    /**
     * 查看结算单明细
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {
        List<TradingLog> tradings = queryChannelService.findAll(QTradingLog.tradingLog.withdraw.id.eq(id), TradingLog.class);
        model.addAttribute("tradings", tradings);
        return "merchant/withdraw/details";
    }

    /**
     * 补充发票信息
     */
    @RequestMapping(value = "/invoice", method = RequestMethod.GET)
    private String invoice(@RequestParam("id") long id, Model model) {
        model.addAttribute("id", id);
        return "merchant/withdraw/invoice";
    }

    /**
     * 补充发票信息
     */
    @RequestMapping(value = "/invoice", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> reject(MerchantWithdrawApply params) {
        try {
            merchantWithdrawApplication.invoiceInfo(params);
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[商户结算申请审核拒绝异常]", e);
            return ImmutableMap.of("status", false, "message", "处理异常");
        }
    }

    /**
     * 条件查询
     */
    private String buildSql(String sql, Map<String, Object> map, MerchantWithdrawApply params) throws ParseException {

        if (params.getStatus() > 0) {
            sql += " and r.status = :status";
            map.put("status", params.getStatus());
        }

        if (!Strings.isNullOrEmpty(params.getBeginTime())) {
            sql += " and r.applyTime >= :btime ";
            map.put("btime", new Date(new SimpleDateFormat("yyyy-MM-dd").parse(params.getBeginTime()).getTime()));
        }

        if (!Strings.isNullOrEmpty(params.getEndTime())) {
            sql += " and r.applyTime <= :etime ";
            map.put("etime", new Date(new SimpleDateFormat("yyyy-MM-dd").parse(params.getEndTime()).getTime()));
        }

        sql += " order by r.applyTime desc";

        return sql;
    }


}
